package com.desay.pangoo.itmt.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.desay.pangoo.common.lite.lang.web.BusinessException;
import com.desay.pangoo.common.lite.lang.web.PangooWebConstant;
import com.desay.pangoo.common.lite.spring.web.ControllerCommonUtils;
import com.desay.pangoo.itmt.controller.vo.BUDivVo;
import com.desay.pangoo.itmt.entity.BUDivEntity;
import com.desay.pangoo.itmt.enums.ExceptionCodeEnum;
import com.desay.pangoo.itmt.repository.BUDivRepository;
import com.desay.pangoo.itmt.repository.spec.ExpandCriteria;
import com.desay.pangoo.itmt.repository.spec.Restrictions;
import com.desay.pangoo.itmt.service.BuDivService;

import cn.hutool.core.collection.CollUtil;

/**
 * @author uidq1163
 */
@Service
public class BuDivServiceImpl implements BuDivService {

	@Autowired
	private BUDivRepository bUDivRepository;

	@Override
	public Long create(BUDivVo vo) {
		BUDivEntity exist = bUDivRepository.findByBu(vo.getBu());
		if (null != exist) {
			throw new BusinessException(ExceptionCodeEnum.BU_HAS_EXIST);
		}
		String user = ControllerCommonUtils.getHeader(PangooWebConstant.HEADER_NAME_USER_FULL_NAME);
		BUDivEntity bUDivEntity = new BUDivEntity();
		BeanUtils.copyProperties(vo, bUDivEntity);
		bUDivEntity.setCreator(user);
		bUDivRepository.save(bUDivEntity);
		return bUDivEntity.getId();
	}

	@Override
	public void delete(Long id) {
		Optional<BUDivEntity> opiton = bUDivRepository.findById(id);
		if (!opiton.isPresent()) {
			throw new BusinessException(ExceptionCodeEnum.BU_NOT_EXIST);
		}
		bUDivRepository.deleteById(id);
	}

	@Override
	public void update(Long id, BUDivVo vo) {
		String user = ControllerCommonUtils.getHeader(PangooWebConstant.HEADER_NAME_USER_FULL_NAME);
		ExpandCriteria<BUDivEntity> c = new ExpandCriteria<>();
		c.add(Restrictions.eq("bu", vo.getBu(), true));
		c.add(Restrictions.ne("id", id, true));
		List<BUDivEntity> list = bUDivRepository.findAll(c);
		if (CollUtil.isNotEmpty(list)) {
			throw new BusinessException(ExceptionCodeEnum.BU_HAS_EXIST);
		}

		Optional<BUDivEntity> opiton = bUDivRepository.findById(id);
		if (!opiton.isPresent()) {
			throw new BusinessException(ExceptionCodeEnum.BU_NOT_EXIST);
		}
		BUDivEntity existEntity = opiton.get();
		BeanUtils.copyProperties(vo, existEntity);
		existEntity.setUpdator(user);
		bUDivRepository.save(existEntity);
	}

	@Override
	public List<BUDivEntity> getAll() {
		ExpandCriteria<BUDivEntity> c = new ExpandCriteria<>();
		Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
		return bUDivRepository.findAll(c,sort);
	}
}
